from forms import *
from datetime import datetime

class PollCreationPage(webapp.RequestHandler):
  def post(self):
    if users.get_current_user():
      data = PollForm(data=self.request.POST)
      if data.is_valid(): 
        poll = Poll(question=self.request.get('question'))
        poll.owner = users.get_current_user()
        if self.request.get("start_date"):
          poll.start_date = datetime.strptime(self.request.get("start_date"), "%Y-%m-%d")
        if self.request.get("end_date"):        
          poll.end_date = datetime.strptime(self.request.get("end_date"), "%Y-%m-%d")
        poll.put()
      
        for choice in self.request.get_all('choices'):
          if choice:
            choice = Choice(name = choice, poll = poll.key())
            choice.put()

        self.redirect('/')
      else:
        url = users.create_login_url(self.request.uri)
        url_linktext = 'Logout'
        template_values = {
          'form': data,
          'url': url,
          'url_linktext': url_linktext,
          }
        path = os.path.join(os.path.dirname(__file__), 'create.html')
        self.response.out.write(template.render(path, template_values))
    else:
      self.redirect('/')
  def get(self):
    if users.get_current_user():
      form = PollForm()
      url = users.create_login_url(self.request.uri)
      url_linktext = 'Logout'
      template_values = {
        'form': form,
        'url': url,
        'url_linktext': url_linktext
        }
      path = os.path.join(os.path.dirname(__file__), 'create.html')
      self.response.out.write(template.render(path, template_values))
    else:
      self.redirect('/')
